// vip/compile/index.js
import {
  toast,
  distance,
  checkPhone
} from '../../utils/util'
import base from '../../api/base'
const app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    saveView: '立即发布',
    tabIndex: 0,
    id: '',
    address: '',
    imgUrl: [],
    info: {},
    enterpriseArray: [],
    enterpriseData: '',
    enterpriseIndex: 0,
    count: 9,
    children: [],
    else: false,
    elseValue: '',
    showList: [],
    attr: [],
    attrIndex: 0
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    console.log(options)
    this._initOptions(options)
  },
  initEnterpriseArray() {
    const code = '004'
    const result = []
    app.$api.common.commonFind({
        code
      })
      .then((res) => {
        const data = res.data
        data.map((item) => {
          result.push(item.name)
        })
        this.setData({
          enterpriseArray: result,
          enterpriseData: data
        })
        this.getCodeDetail()
      }).catch((e) => {
        toast('请稍后再试', 1000)
      })
  },
  getCodeDetail() {
    const code = this.data.info.enttype
    console.log(code)
    const array = this.data.enterpriseData
    array.map((item, index) => {
      if (item.code === code) {
        this.setData({
          enterpriseIndex: index
        })
      }
    })
    console.log(this.data.enterpriseIndex)
  },
  _initOptions(options) {
    this.setData({
      tabIndex: Number(options.index)
    })
    if (options.info) {
      const info = JSON.parse(options.info)
      if (Number(options.index) === 0) {
        console.log(options.code)
        this.changeAttr(options.code)
      }
      if (info.equtype) {
        info.equtype = options.code
        info.equname = options.equipment
        const imgUrl = this.bindImgurl(info.equimgurl)
        this.setData({
          imgUrl,
          info
        })
      } else if (info.entscope) {
        info.entscope = options.equipment
        const imgUrl = this.bindImgurl(info.imgurl)
        this.setData({
          info,
          imgUrl
        })
        this.initEnterpriseArray()
      } else if (info.maintainscope) {
        info.maintainscope = options.equipment
        const imgUrl = this.bindImgurl(info.imgurl)
        this.setData({
          info,
          imgUrl
        })
      }
      this.bindAddress()
      return
    }
    const index = options.index
    this.setData({
      tabIndex: Number(index),
      id: options.id
    })
    Number(index) === 0 ? this.getRentDetail(options.id, index) : Number(index) === 1 ? this.getSellDetail(options.id, index) : this.getMaintainDetail(options.id, index)
  },
  changeAttr(code) {
    const result = []
    const children = []
    const attr = []
    const showList = []
    app.$api.common.commonFind({
      code
    }).then((res) => {
      const data = res.data
      data.map((item, index) => {
        result.push({
          name: item.name
        })
        children.push({
          index,
          data: item.children
        })
        attr.push({
          name: '请选择'
        })
        showList.push(false)
      })
      this.setData({
        codeArray: result,
        children,
        attr,
        showList
      })
    }).catch((res) => {
      toast('请稍后再试', 1000)
    })
  },
  getRentDetail(id, index) {
    const result = []
    const children = []
    const showList = []
    app.$api.index.rentDetail({
        id
      })
      .then((res) => {
        const data = res.data
        console.log(data)
        const distance = this.calcDistance(data)
        const info = Object.assign({}, data, {
          index,
          distance,
        })
        if (info.equattr.length) {
          this.setData({
            attr: JSON.parse(info.equattr)
          })
          app.$api.common.commonFind({
            code: info.equtype
          }).then((e) => {
            const edata = e.data
            edata.map((item, index) => {
              result.push({
                name: item.name
              })
              children.push({
                index,
                data: item.children
              })
              showList.push(false)
            })
            this.setData({
              children,
              showList,
              codeArray: result
            })
          }).catch((e) => {
            tosat('请稍后再试', 1000)
          })
        }
        const imgUrl = this.bindImgurl(info.equimgurl)
        this.setData({
          info,
          imgUrl
        })
        this.bindAddress()
      }).catch((e) => {
        toast('请稍后再试', 1000)
      })
  },
  getSellDetail(id, index) {
    app.$api.index.saleDetail({
        id
      })
      .then((res) => {
        const data = res.data
        const distance = this.calcDistance(data)
        const info = Object.assign({}, data, {
          index,
          distance
        })
        const imgUrl = this.bindImgurl(info.imgurl)
        this.setData({
          info,
          imgUrl
        })
        console.log(data)
        this.bindAddress()
        this.initEnterpriseArray()
      }).catch((e) => {
        toast('请稍后再试', 1000)
      })
  },
  getMaintainDetail(id, index) {
    app.$api.index.maintainDetail({
        id
      })
      .then((res) => {
        const data = res.data
        const distance = this.calcDistance(data)
        const info = Object.assign({}, data, {
          index,
          distance
        })
        const imgUrl = this.bindImgurl(info.imgurl)
        this.setData({
          info,
          imgUrl
        })
        this.bindAddress()
      }).catch((e) => {
        toast('请稍后再试', 1000)
      })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },
  calcDistance(item) {
    const locationA = {
      lat: wx.getStorageSync('location').lat,
      lng: wx.getStorageSync('location').lng
    }
    const locationB = {
      lat: Number(item.lat),
      lng: Number(item.lon)
    }
    const distanceValue = distance(locationA, locationB)
    return distanceValue
  },
  bindAddress() {
    const result = []
    const regArr = ['区', '县', '旗', '市', '岛', '仔']
    const address = this.data.info.detailedaddress
    console.log(address)
    const reAddress = address.split('').reverse().join('')
    const count = address.split('').reduce((a, v) => {
      a = v === '区' ? a + 1 : a + 0
      return a
    }, 0)
    regArr.map((item) => {
      if (item === '区' && count >= 2) {
        result.push(reAddress.lastIndexOf(item))
      } else if (reAddress.indexOf(item) > -1 && count < 2) {
        result.push(reAddress.indexOf(item))
      }
    })
    this.setData({
      address: address.substring(0, address.length - result[0])
    })
  },
  bindImgurl(imgurl) {
    const imgUrl = imgurl.split(',').map((item) => {
      return `${base.pro}/common/viewImage?imagepath=${item}`
    })
    return imgUrl
  },
  bindClassify() {
    const entry = 'compile'
    const index = this.data.tabIndex
    const result = []
    const {
      imgUrl,
      date
    } = app.globalData
    imgUrl.map((item) => {
      result.push(JSON.parse(item).fileUrl)
    })
    if (imgUrl.length) {
      if (this.data.tabIndex === 0) {
        const equimgurl = 'info.equimgurl'
        const equattr = 'info.equattr'
        this.setData({
          [equimgurl]: result.join(','),
          [equattr]: JSON.stringify(this.data.attr)
        })
      } else {
        const imgurl = 'info.imgurl'
        this.setData({
          [imgurl]: result.join(',')
        })
      }
    }
    if (date.length) {
      const freedate = 'info.freedate'
      this.setData({
        [freedate]: date.join(',')
      })
    }
    const info = JSON.stringify(this.data.info)
    wx.navigateTo({
      url: `/pages/classify/index?index=${index}&entry=${entry}&id=${this.data.id}&info=${info}`,
    })
  },
  handleRent(e) {
    const {
      value
    } = e.detail
    const shortprice = 'info.shortprice'
    this.setData({
      [shortprice]: value
    })
  },
  handleLongRent(e) {
    const {
      value
    } = e.detail
    const longprice = 'info.longprice'
    this.setData({
      [longprice]: value
    })
  },
  bindPickerChange(e) {
    const index = e.detail.value
    const enttype = 'info.enttype'
    this.setData({
      enterpriseIndex: index,
      [enttype]: this.data.enterpriseData[index].code
    })
    console.log(this.data.enterpriseData[index].code)
  },
  handleCompany(e) {
    const content = e.detail.value
    const companyname = 'info.companyname'
    this.setData({
      [companyname]: content
    })
  },
  handleContact(e) {
    const content = e.detail.value
    const linkname = 'info.linkname'
    this.setData({
      [linkname]: content
    })
  },
  handlePhone(e) {
    const content = e.detail.value
    const phone = 'info.phone'
    this.setData({
      [phone]: content
    })
  },
  bindAddress2(params) {
    console.log(params)
    const address = params.detail.address
    const latitude = params.detail.latitude
    const longitude = params.detail.longitude
    const detailedaddress = 'info.detailedaddress'
    const lat = 'info.lat'
    const lon = 'info.lon'
    if (address.indexOf('省') < 0) {
      const qqmapsdk = new QQMapWX({
        key: base.subkey // 必填
      })
      qqmapsdk.reverseGeocoder({
        location: {
          latitude: params.detail.latitude,
          longitude: params.detail.longitude
        },
        success(res) {
          this.setData({
            [detailedaddress]: res.result.address,
            [lat]: latitude,
            [lon]: longitude
          })
          this.bindAddress()
        }
      })
    } else {
      this.setData({
        [detailedaddress]: address,
        [lat]: latitude,
        [lon]: longitude
      })
      this.bindAddress()
    }
  },
  handleIntroduce(e) {
    const content = e.detail.value
    const entprofile = 'info.entprofile'
    this.setData({
      [entprofile]: content
    })
    console.log(this.data.info.entprofile)
  },
  bindPublish() {
    const flag = this.validateCommon()
    if (flag) {
      this.publish()
    }
  },
  publish() {
    const {
      tabIndex
    } = this.data
    const result = []
    const {
      date,
      imgUrl
    } = app.globalData
    imgUrl.map((item) => {
      result.push(JSON.parse(item).fileUrl)
    })
    if (imgUrl.length) {
      if (this.data.tabIndex === 0) {
        const equimgurl = 'info.equimgurl'
        this.setData({
          [equimgurl]: result.join(',')
        })
      } else {
        const imgurl = 'info.imgurl'
        this.setData({
          [imgurl]: result.join(',')
        })
      }
    }
    if (date.length) {
      const freedate = 'info.freedate'
      this.setData({
        [freedate]: date.join(',')
      })
    }
    tabIndex === 0 ? this.fixRent() : tabIndex === 1 ? this.fixSell() : this.fixMaintain()
  },
  fixRent() {
    const _this = this.data.info
    const newShort = _this.shortprice ? _this.shortprice : ''
    const newLong = _this.longprice ? _this.longprice : ''
    const info = {
      id: _this.id,
      freedate: _this.freedate,
      equname: _this.equname,
      shortprice: newShort,
      longprice: newLong,
      companyname: _this.companyname,
      equtype: _this.equtype,
      phone: _this.phone,
      lon: _this.lon,
      lat: _this.lat,
      detailedaddress: _this.detailedaddress,
      equimgurl: _this.equimgurl,
      linkname: _this.linkname,
      equattr: JSON.stringify(this.data.attr),
      equprofile: _this.equprofile
    }
    app.$api.publish.rentUpdate({
        ...info
      })
      .then((res) => {
        wx.showToast({
          title: '修改成功',
          icon: 'success',
          duration: 1000
        })
        setTimeout(() => {
          wx.navigateTo({
            url: '/personal/myPubLish/index'
          })
        }, 1000)
      }).catch((e) => {
        toast('请稍后再试', 1000)
      })
  },
  fixSell() {
    const _this = this.data.info
    const info = {
      id: _this.id,
      enttype: _this.enttype,
      entscope: _this.entscope,
      entprofile: _this.entprofile,
      companyname: _this.companyname,
      phone: _this.phone,
      lon: _this.lon,
      lat: _this.lat,
      detailedaddress: _this.detailedaddress,
      imgurl: _this.imgurl,
      linkname: _this.linkname
    }
    app.$api.publish.saleUpdate({
        ...info
      })
      .then((res) => {
        wx.showToast({
          title: '修改成功',
          icon: 'success',
          duration: 1000
        })
        setTimeout(() => {
          wx.navigateTo({
            url: '/personal/myPubLish/index'
          })
        }, 1000)
      }).catch((e) => {
        toast('请稍后再试', 1000)
      })
  },
  fixMaintain() {
    const _this = this.data.info
    const info = {
      id: _this.id,
      entprofile: _this.entprofile,
      maintainscope: _this.maintainscope,
      companyname: _this.companyname,
      phone: _this.phone,
      lon: _this.lon,
      lat: _this.lat,
      detailedaddress: _this.detailedaddress,
      imgurl: _this.imgurl,
      linkname: _this.linkname
    }
    app.$api.publish.maintainUpdate({
        ...info
      })
      .then((res) => {
        wx.showToast({
          title: '修改成功',
          icon: 'success',
          duration: 1000
        })
        setTimeout(() => {
          wx.navigateTo({
            url: '/personal/myPubLish/index'
          })
        }, 1000)
      }).catch((e) => {
        toast('请稍后再试', 1000)
      })
  },
  validateCommon() {
    const {
      companyname,
      linkname,
      phone
    } = this.data.info
    const {
      entname,
      username
    } = wx.getStorageSync('userInfo')
    if (this.data.tabIndex !== 0 && companyname.trim() === '') {
      toast('公司地址不能为空', 1000)
      return false
    }
    if (this.data.tabIndex.index === 0) {
      const flag = attr.map((item) => {
        return item.name === '请选择'
      })
      if (flag.indexOf(true) > -1) {
        toast('设备属性不能为空', 1000)
        return false
      }
    }
    if (linkname.trim() === '') {
      toast('联系人姓名不能为空', 1000)
      return false
    }
    if (!checkPhone(phone)) {
      toast('联系电话格式不正确', 1000)
      return false
    }
    return true
  },
  bindChangeShow(e) {
    const {
      index
    } = e.currentTarget.dataset
    const {
      showList
    } = this.data
    const list = showList.map((item, idx) => {
      return index === idx
    })
    this.setData({
      showList: list,
      attrIndex: index
    })
  },
  onCancel() {
    const {
      showList
    } = this.data
    const list = showList.map((item, idx) => {
      return false
    })
    this.setData({
      showList: list
    })
    console.log(this.data.showList)
  },
  onConfirm(e) {
    const {
      index
    } = e.currentTarget.dataset
    const {
      name,
      code
    } = e.detail.value
    // const subIndex = e.detail.index
    const {
      showList,
      attr
    } = this.data
    attr[index] = {
      name,
      code
    }
    if (name === '其他') {
      this.setData({
        else: true
      })
    } else {
      attr[index] = {
        name,
        code
      }
    }
    const list = showList.map((item, idx) => {
      return false
    })
    this.setData({
      showList: list,
      attr
    })
  },
  bindElseConfirm(e) {
    const {
      attr,
      attrIndex
    } = this.data
    console.log(attrIndex)
    attr[attrIndex].name = this.data.elseValue
    this.setData({
      else: false,
      attr
    })
  },
  bindElseClose(e) {
    this.setData({
      else: false
    })
  },
  bindGetElseContent(e) {
    const content = e.detail.value
    console.log(content)
    this.setData({
      elseValue: content
    })
    if (this.data.elseValue.trim() === '') {
      this.setData({
        elseValue: '请选择'
      })
    }
  }
})